<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/27.
 */

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\EditTrait;
use App\Http\Controllers\Traits\ExtendTrait;
use App\Http\Controllers\Traits\StoreTrait;
use App\Http\Controllers\Traits\ValidateTrait;
use App\Models\Permission;
use App\Utils\ResultsVo;

class PermissionController extends Controller
{
    use EditTrait;
    use ExtendTrait;
    use StoreTrait;
    use ValidateTrait;

    public function index(): \Illuminate\Http\JsonResponse
    {
        $per = Permission::query()->select([
            'id', 'parent_id', 'title', 'name', 'status', 'route', 'component', 'weight', 'type', 'is_nav', 'icon',
        ])->orderBy('weight', 'desc')->get()->toArray();
        $per = infiniteTree($per);

        return ResultsVo::success(['results' => $per]);
    }

    public function lists(): \Illuminate\Http\JsonResponse
    {
        $results = Permission::query()->select([
            'id', 'parent_id', 'title',
        ])->orderBy('weight', 'desc')->get()->toArray();
        $data = $result = [];
        infiniteLevel($results, $data);

        $result[] = ['value' => 0, 'label' => '顶级栏目'];
        foreach ($data as $item) {
            if ($item['lv'] > 0) {
                $item['title'] = '|'.str_repeat('-', $item['lv']).$item['title'];
            }
            $result[] = [
                'value' => $item['id'],
                'label' => $item['title'],
            ];
        }

        return ResultsVo::success($result);
    }
}
